package com.lxm.shownews.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.content.SharedPreferencesCompat;

import java.util.Map;

/**
 * Created by lxm on 2016/1/28.
 */
public class SPUtils {

    public static final String SHARED_CHANNEL = "channel";
    public static final String SHARED_LAUNCHNUM = "launchNum";
    private Context context;

    public static void put(Context context, String sharedName, String key, Object value) {
        SharedPreferences sp = context.getSharedPreferences(sharedName, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        if (value instanceof String) {
            edit.putString(key, (String) value);
        } else if (value instanceof Integer) {
            edit.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            edit.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            edit.putFloat(key, (Float) value);
        } else if (value instanceof Long) {
            edit.putLong(key, (Long) value);
        } else {
            edit.putString(key, value.toString());
        }
        SharedPreferencesCompat.EditorCompat.getInstance().apply(edit);
    }

    public static Object get(Context context, String sharedName, String key, Object defaultValue) {
        SharedPreferences sp = context.getSharedPreferences(sharedName, Context.MODE_PRIVATE);
        if (defaultValue instanceof String) {
            return sp.getString(key, (String) defaultValue);
        } else if (defaultValue instanceof Integer) {
            return sp.getInt(key, (Integer) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultValue);
        } else if (defaultValue instanceof Float) {
            return sp.getFloat(key, (Float) defaultValue);
        } else if (defaultValue instanceof Long) {
            return sp.getLong(key, (Long) defaultValue);
        }
        return null;
    }

    public static Map<String, Object> getAll(Context context, String sharedName) {
        SharedPreferences sp = context.getSharedPreferences(sharedName, Context.MODE_PRIVATE);
        return (Map<String, Object>) sp.getAll();
    }


}
